package com.commerceE.managedBean;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.primefaces.event.RowEditEvent;

import com.commerceE.common.exception.ServiceException;
import com.commerceE.domain.Category;
import com.commerceE.service.CategoryService;
import com.commerceE.util.SpringUtil;

@ManagedBean(name="categoryBean")
@RequestScoped
public class CategoryBean {

	private List<Category> categoryList;
	
	private Category newCategory ;
	
	private Category selectedCategory;
	
	private CategoryService categoryService;

	public CategoryBean() {
		newCategory = new Category();
		newCategory.setParentCategoryId("-1");
		categoryService = (CategoryService)SpringUtil.getBeanById("categoryService");
		try {
			categoryList = categoryService.getAllListOfCategory();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}
	
	public void addCategory(){
		try {
			categoryService.insertCategory(newCategory);
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		newCategory = new Category();
		categoryList.add(newCategory);
	}
	
	public void onDelete(){
		FacesMessage msg = null;
    	try {
			categoryService.deleteCategory(selectedCategory);
		} catch (ServiceException e) {
			e.printStackTrace();
			 msg = new FacesMessage(e.getMessage(), selectedCategory.getCategoryName());
		}
		if(msg==null){
			categoryList.remove(selectedCategory);
			msg = new FacesMessage("Category deleted. ", selectedCategory.getCategoryName());
		}
        FacesContext.getCurrentInstance().addMessage(null, msg);   
	}
	
	public void onEdit(RowEditEvent event) { 
		Category category = (Category) event.getObject();
		FacesMessage msg = null;
		try {
			categoryService.updateCategory(selectedCategory);
		} catch (ServiceException e) {
			e.printStackTrace();
			 msg = new FacesMessage(e.getMessage(), category.getCategoryName());
		}
		if(msg==null){
			msg = new FacesMessage("Category Edited. ", category.getCategoryName());
		}
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    }  
      
	public List<Category> getCategoryList() {
		return categoryList;
	}

	public void setCategoryList(List<Category> categoryList) {
		this.categoryList = categoryList;
	}

	public Category getNewCategory() {
		return newCategory;
	}

	public void setNewCategory(Category newCategory) {
		this.newCategory = newCategory;
	}

	public Category getSelectedCategory() {
		return selectedCategory;
	}

	public void setSelectedCategory(Category selectedCategory) {
		this.selectedCategory = selectedCategory;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

 
}
